<template>
  <el-card :class="[prefixCls]" shadow="never">
    <div class="flex items-center">
      <span class="text-16px font-700">渠道管理</span>
      <div class="flex pl-20px flex-grow"></div>
    </div>

    <wd-crud ref="crudRef" :columns="columns" :crud="crud">
      <!-- 分享 -->
      <template #share="{ record }">
        <el-text type="primary" @click="showQr(record)"> 
          <icon icon="vi-ant-design:qrcode-outlined" :size="24"></icon>
           </el-text>
      </template>

      <!-- 状态列 -->
      <template #agent_status="{ record }">
        <el-switch
          v-if="record.agent_status !== undefined"
          v-model="record.agent_status"
          @change="changeStatus($event, record.agent_id)"
          :active-value="20"
          :inactive-value="0"
        ></el-switch>
      </template>

      <template #operationBeforeExtend="{ record }">
        <el-link type="primary" class="mx-1">
          <icon icon="vi-tdesign:user-locked" :size="14" class="mr-1"> </icon>
          <span class="text-sm" @click="editAccount(record)">账号管理 </span>
        </el-link>
      </template>
    </wd-crud>
  </el-card>

  <Dialog v-model="accountVisible" title="账号管理">
    <Form :schema="formSchema" :rules="rules" @register="formRegister" />
    <template #footer>
      <BaseButton type="primary" @click="formSubmit">{{
        t("dialogDemo.submit")
      }}</BaseButton>
      <BaseButton @click="closeAccount()">{{
        t("dialogDemo.close")
      }}</BaseButton>
    </template>
  </Dialog>

  <el-dialog
    v-model="qrCodeDialog"
    title="预览"
    width="350px"
    @close="resetQrDialog"
  >
    <div>
      <el-radio-group v-model="qrTheme" size="small" class="mb2">
        <el-radio-button :value="'theme1'">主题1</el-radio-button>
        <el-radio-button :value="'theme2'">主题2</el-radio-button>
        <el-radio-button :value="'theme3'">主题3</el-radio-button>
      </el-radio-group>

      <div v-if="qrcodeImg" v-viewer class="code">
        <Qrcode
        :text="qrcodeImg"
        :width="220"
      />
      </div>
      <div v-else class="text-center text-gray-500 mt-4">暂无二维码数据</div>
    </div>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, computed, nextTick, unref, watch } from "vue";
import { useDesign } from "@/hooks/web/useDesign";
import { useI18n } from "@/hooks/web/useI18n";
import agentApi from "@/apis/agent";
import WdCrud from "@cwd/wd-crud";
import { message } from "@/utils/message";
import { useForm } from "@/hooks/web/useForm";
import { useValidator } from "@/hooks/web/useValidator";
import Qrcode from "@cps/common/Qrcode/index.vue";
import { useUserStoreWithOut} from "@/store/modules/user";

const userStore = useUserStoreWithOut();

console.log("userStore", userStore.userInfo);

const { formRegister, formMethods } = useForm();
const { setValues, getElFormExpose, getFormData } = formMethods;

const { required, lengthRange } = useValidator();
const accountVisible = ref(false);

const { t } = useI18n();
const { getPrefixCls } = useDesign();
const prefixCls = getPrefixCls("content-wrap");

const qrCodeDialog = ref(false);
const qrTheme = ref("theme1");
const currentItem = ref({});
const qrcodeImg = ref("");
// 打开二维码弹窗
const showQr = (item) => {
  currentItem.value = item;
  qrTheme.value = "theme1"; // 默认选中
  qrcodeImg.value = item?.theme1 || "";
  qrCodeDialog.value = true;
};
// 弹窗关闭时重置数据
const resetQrDialog = () => {
  qrCodeDialog.value = false;
  qrTheme.value = "theme1";
  qrcodeImg.value = "";
  currentItem.value = {};
};
watch(qrTheme, (newTheme) => {
  if (currentItem.value && currentItem.value[newTheme]) {
    qrcodeImg.value = currentItem.value[newTheme];
  }
});
const crudRef = ref(null);

const crud = reactive({
  pk: "agent_id",
  api: agentApi.getList,
  showIndex: false,
  pageLayout: "fixed",
  operationColumn: true,
  operationColumnWidth: 260,
  add: { show: !userStore.userInfo.parent_id, api: agentApi.save, auth: ["agent:save"] },
  edit: { show: !userStore.userInfo.parent_id, api: agentApi.update, auth: ["agent:update"] },
  formOption: { viewType: "dialog", width: "60%" },
  isExpand: true,
  beforeOpenAdd: () => {
    return true;
  },
  beforeEdit: (params) => {
    delete params.children;
    return true;
  },
});

const columns = reactive([
  {
    title: "ID",
    dataIndex: "agent_id",
    addDisplay: false,
    editDisplay: false,
    width: 50,
    hide: true,
  },

  {
    title: "名称",
    dataIndex: "agent_name",
    search: true,
    commonRules: [{ required: true, message: "经销商名称必填" }],
    width: 280,
    textAlign: "left",
  },
  {
    title: "分享",
    dataIndex: "share",
    addDisplay: false,
    editDisplay: false,
    width: 150,
  },
  {
    title: "公司名称",
    dataIndex: "company_name",
    commonRules: [{ required: true, message: "公司名称必填" }],
    width: 150,
  },
  {
    title: "登录账号",
    dataIndex: "account",
    commonRules: [{ required: true, message: "登录账号必填" }],
    width: 150,
    hide: true,
  },
  {
    title: "截至日期",
    dataIndex: "valid_end_date",
    commonRules: [{ required: true, message: "截至日期必填" }],
    width: 150,
    formType: "date",
    hide: true,
  },
  {
    title: "备注",
    dataIndex: "remark",
    formType: "textarea",
    width: 150,
    hide: true,
  },
  {
    title: "状态",
    dataIndex: "agent_status",
    search: true,
    formType: "radio",
    dict: {
      data: [
        { label: "正常", value: 20 },
        { label: "禁用", value: 0 },
      ],
    },
    addDefaultValue: 20,
    width: 120,
  },
  {
    title: "创建时间",
    dataIndex: "create_time",
    addDisplay: false,
    editDisplay: false,
    search: false,
    width: 180,
  },
]);
const changeStatus = async (status, id) => {
  const response = await agentApi.changeStatus({ id, status });
  if (response.success) {
    message(response.message, { type: "success" });
  }
};

const editAccount = async (record) => {
  accountVisible.value = true;
  await nextTick();
  formMethods.setValues({
    account: record.account,
    agent_id: record.agent_id,
    password: "", // 密码默认留空，如非编辑可省略
  });
};
const closeAccount = () => {
  accountVisible.value = false;
};
//账号信息修改
const formSubmit = async () => {
  const accountForm = await formMethods.getElFormExpose();
  if (!accountForm) return;

  try {
    await accountForm.validate();

    // ✅ 获取表单字段内容
    const formData = await formMethods.getFormData();
    // ✅ 执行提交请求
    const response = await agentApi.modifyAccountInfo(formData.agent_id, {
      ...formData,
    });

    // ✅ 响应处理
    if (response.success) {
      accountVisible.value = false;
      accountForm.resetFields();
      crudRef.value.refresh();
      message(response.message, { type: "success" });
    }
  } catch (err) {
    console.warn("表单校验未通过:", err);
  }
};
const formSchema = reactive([
  {
    field: "agent_id",
    label: "登录账号",
    component: "Input",
    hidden: true,
  },
  {
    field: "account",
    label: "登录账号",
    component: "Input",
    formItemProps: {
      rules: [required()],
    },
    colProps: {
      span: 24,
    },
  },
  {
    field: "newPassword",
    label: "新密码",
    component: "InputPassword",
    colProps: {
      span: 24,
    },
    componentProps: {
      strength: true,
    },
  },
  {
    field: "newPassword_confirmation",
    label: "确认新密码",
    component: "InputPassword",
    colProps: {
      span: 24,
    },
    componentProps: {
      strength: true,
    },
  },
]);

const rules = reactive({
  account: [required()],
  newPassword: [
    required(),
    {
      asyncValidator: async (_, val, callback) => {
        const formData = await getFormData();
        if (val !== formData.newPassword_confirmation) {
          callback(new Error("新密码与确认新密码不一致"));
        } else {
          callback();
        }
      },
    },
  ],
  newPassword_confirmation: [
    required(),
    {
      asyncValidator: async (_, val, callback) => {
        const formData = await getFormData();
        if (val !== formData.newPassword) {
          callback(new Error("确认新密码与新密码不一致"));
        } else {
          callback();
        }
      },
    },
  ],
});
</script>
<style scoped>
.code {
  display: flex;
  justify-content: center;
  align-items: center;
}
.bicode {
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 6px;
  background-color: #fff;
}
</style>